<?php

namespace App\Http\Middleware;

use App\Models\UserModel;
use Closure;
use Framework\BaseService;
use Framework\Helper;
use Framework\Hope;
use Illuminate\Http\Request;

class UuidMiddleware extends BaseService
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $params = json_decode($request->header('sign'),true);
        if (!array_key_exists('sign', $params)
            || !array_key_exists('sign_timestamp', $params)
            || !array_key_exists('sign_uuid', $params) ) {
            $this->retError("缺少签名参数");
        }
        $user_id = Hope::getLoginId();
        $uuid = UserModel::query()->where('id',$user_id)->value('uuid');
        $now = time();
        $timestamp = $params['sign_timestamp'];
        if (abs($now - $timestamp/1000) > 60 * 10) {
            $this->retError("签名已过期");
        }
        $sign = md5($uuid.$params['sign_timestamp'].'huimin');
        if ($sign!== $params['sign']) {
            return $this->retError('设备验证不通过');
        }

        return $next($request);
    }

}
